package com.xzzz.irda.codegen.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xzzz.irda.codegen.mapper.MysqlGeneratorMapper;
import com.xzzz.irda.codegen.pojo.ColumnDO;
import com.xzzz.irda.codegen.pojo.TableDO;
import com.xzzz.irda.codegen.utils.GenUtils;
import com.xzzz.irda.codegen.utils.IoUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成器
 *
 * @author xzzz
 * 
 */
@Slf4j
@Service("generatorService")
public class GeneratorService {

	@Autowired
	private MysqlGeneratorMapper mysqlGeneratorMapper;

	/**
	 * 根据 TableName 查询 table 信息列表
	 *
	 * @param tableName 表名
	 * @return PageResult<TableDO>
	 */
	public PageInfo<TableDO> listTablesByTableName(String tableName) {
		PageHelper.startPage(1, 20).doSelectPageInfo(() -> mysqlGeneratorMapper.listTableColumnsByTableName(tableName));
		List<TableDO> tableList = mysqlGeneratorMapper.listTablesByTableName(tableName);
		if (tableList == null) {
			tableList = new ArrayList<>();
		}

		return new PageInfo<>(tableList);
	}

	/**
	 * 根据 TableName 查询 table 信息
	 *
	 * @param tableName 表名
	 * @return TableDO
	 */
	TableDO getTableByTableName(String tableName) {
		return mysqlGeneratorMapper.getTableByTableName(tableName);
	}

	/**
	 * 根据 TableName 查询 table 的列信息列表
	 *
	 * @param tableName 表名
	 * @return List<ColumnDO>
	 */
	public List<ColumnDO> listTableColumnsByTableName(String tableName) {
		return mysqlGeneratorMapper.listTableColumnsByTableName(tableName);
	}

	/**
	 * 根据表名去生成代码
	 *
	 * @param tableNames 表名数组
	 * @return byte[]
	 */
	public byte[] generatorCode(String[] tableNames) {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		ZipOutputStream zip = new ZipOutputStream(outputStream);

		List<TableDO> tableDoList = new ArrayList<>();
		for (String tableName : tableNames) {
			// 查询表信息
			TableDO table = getTableByTableName(tableName);
			// 查询列信息
			List<ColumnDO> columnList = listTableColumnsByTableName(tableName);
			table.setColumns(columnList);
			tableDoList.add(table);
		}
		//生成代码
		GenUtils.generatorCode(tableDoList, zip);
		try {
			IoUtil.close(zip);
		} catch (IOException e) {
			throw new RuntimeException("生成代码时，流关闭失败");
		}
		return outputStream.toByteArray();
	}
}
